/**
 * Created by Dalyn on 2017/5/8.
 */
import React from "react";
import {hashHistory} from 'react-router';
import Relay from "react-relay";
import {_Input,_Icon} from 'ANT_DE';
const Input = _Input,
    Icon = _Icon;

import {message} from 'antd';

import {Modal,Button} from 'fly';


import SavePackStepMutation from '../mutation/ProductionDigestImageMutation/SaveProDigestMutation';  //保存

import DelQiniuFileMutation from "../mutation/DelQiniuFileMutation" // 删除图片

import GetQiNiuToken from "../mutation/GetQiNiuTokenMutation"  //上传图片获取token

import GetProDigestMutation from '../mutation/ProductionDigestImageMutation/GetProDigestMutation'  //获取上次保存的接口读取
import '../css/packStep.css';

// 细分组件
import {Header,PackList,ViewImgList,ViewAAddImg} from '../components/PackStep_Header';

import AddImgModal from "../components/AddImgModal";  //上传图片
import FileUpData from '../components/FileUpDataPro'  //上传附件
import Config from "../../../../util/Config"
/*
 * 包装步骤  展示层
 * */

/*导出组件*/
export default class A extends React.Component{

    constructor(props) {
        super(props);
        this.state = {
            fileList:[],   //上傳文件列表
            previewImage: '',
            previewVisible:false,  //图片预览
            token:"",

            fileUpdataList:[],  //上传附件的list
            picRemoveList:[],   //临时删除图片的列表
            dis_btn:false
        };

        this.FixedImgSrc = Config.qiuniu;

        this.handlePreview = this.handlePreview.bind(this);
        this.handleCancel = this.handleCancel.bind(this);
        this.save = this.save.bind(this);

        this.handleChangeText = this.handleChangeText.bind(this);

        this.picRemove = this.picRemove.bind(this);
        this.beforeUpload = this.beforeUpload.bind(this);

        this.addImg = this.addImg.bind(this);

        this.addImg = this.addImg.bind(this);
        this.addFileImg = this.addFileImg.bind(this);

        this.addFileItem = this.addFileItem.bind(this); //上传文件 更新内部状态list
    }

    componentWillMount(){
        this.pdId = this.props.pdId;

        // 获得上次保存的数据as

        Relay.Store.commitUpdate(new GetProDigestMutation({
                pdId:this.pdId
            }),{
                onSuccess:(res)=>{
                    let data = res.getProDigest.responseData;
                    if(data.errorCode == 0){
                        let con_img = data.proDigestModel.imgJSON,
                              arr = [];

                        (!con_img) ? arr = [] : arr = JSON.parse(con_img);

                        this.setState({fileList:arr})
                    }
                },
                onFailure:()=>{
                    message.error("拉取数据失败，请检查网络连接")
                }
            }
        );


        //获取上传图片所需的token
        Relay.Store.commitUpdate(
            new GetQiNiuToken({}), {
                onSuccess: (res) => {
                    let errorCode = res.getQiNiuToken.getQiNiuToken.errorCode;
                    if(errorCode==0){
                        let qiniutoken = res.getQiNiuToken.getQiNiuToken.qiniutoken;
                        this.setState({
                            token:qiniutoken
                        })
                    }
                }
            }
        );
    }

    componentDidMount(){
    }

    componentWillUnmount(){
    }

    //  验证格式需要通过obj传递到另一个组件调用，必须要在当前proto原型上，不可添加到自由属性.
    accept = ".jpg,.png,.gif,.jpeg,.bmp";
    fileAccept = ".pdf,.xlsx,.xls,.docx,.doc";

    /*文本输入change*/
    handleChangeText = (e,index)=>{
        this.state.stepArr[index].value = e.target.value;
        this.setState({
            stepArr:this.state.stepArr
        });
    };

    // 删除图片
    picRemove(index){
        //下列固定为0，因为list最多只能上传一个，固0
        const Rn =  this.state.fileList[index].file.response.key;
        //过渡动画
        this.state.fileList[index].file.__transClass = "leave";
        // 伪更新
        this.setState({ fileList:this.state.fileList });
        // 记录删除操作;
        this.state.picRemoveList.push(Rn);
        setTimeout(()=>{
            this.state.fileList.splice(index,1);
            this.setState({
                fileList:this.state.fileList
            })
        },300)
    }

    save(){
        // 锁定disabled
        this.setState({dis_btn:true});

        let fileList = this.state.fileList;

        Relay.Store.commitUpdate(
            new SavePackStepMutation({
                pdId:this.pdId,
                imgJSON:JSON.stringify(fileList)
            }), {
                onFailure: (err) => {
                    message.error("网络请求失败")
                },
                onSuccess: (res)=> {
                    message.success("保存成功");
                    setTimeout(()=>{
                        // 锁定disabled
                        this.setState({dis_btn:false});
                    },300)
                }
            }
        );

        let R = this.state.picRemoveList;

        if(R.length === 0 ){ return; }

        Relay.Store.commitUpdate(
            new DelQiniuFileMutation({
                fileKey: R.join(",")
            }),
            {
                onFailure: () => {
                },
                onSuccess: (response) => {
                    let errorCode = response.delQiniuFile.delQiniuFile.errorCode;
                    if (errorCode == 0) {
                        this.setState({picRemoveList:[]});
                    }else{
                        message.error("删除图片失败，请重试")
                    }
                }
            }
        )
    }

    // 预览图片关闭
    handleCancel = ()=>{
        this.setState({
            previewVisible:false,
        })
        // 优化用户体验，延时一秒清空图片
        setTimeout(()=>{
            this.setState({
                previewImage:""
            })
        },700);
    }

    // 上传之前进行验证
    beforeUpload(file){
        const MaxSize = 8;  //最大限度 8M;
        // 图片格式
        if(file.type !== "image/jpeg" && file.type !== "image/jpg" && file.type !== "image/png" && file.type !== "image/gif" && file.type !== "image/bmp"){
            message.error("图片格式错误");
            return false;
        }

        // 图片大小
        if( file.size / 1024 / 1024 > MaxSize ){
            message.error("图片大小超过限制");
            return false;
        }

    }

    // 预览图片
    handlePreview = (index) => {
        this.setState({
            previewVisible:true,
            previewImage:this.FixedImgSrc + this.state.fileList[index].file.response.key
        })
    };

    // 添加图片
    addImg(){
        if(this.state.fileList.length < 20){
            this.refs.addFileImgModal.setState({
                visible:true
            })
        }else{
            message.error("图片最多上传20张，您已超过上限")
        }
    }


    //上传图片配置
    uploadPlugin = {
        className:"packagSteps_updata",
        action:"http://up-z2.qiniu.com",
        beforeUpload:this.beforeUpload,
        listType:"picture-card",
        accept:this.accept,
    };


    // 新增图片函数  (push 到当前组件)
    addFileImg({file,text}){
        if(this.state.fileList.length < 20) {
            if (file) {
                this.state.fileList.push({file,text});
                this.setState({
                    fileList: this.state.fileList
                })
            }
        }else{
            message.error("最多只可上传20张");
        }
    }

    // 新增文件函数，（push 当前组件）
    addFileItem(fileList){
        this.state.fileUpdataList = fileList;
        this.setState({
            fileUpdataList:this.state.fileUpdataList
        })
    }

    render(){
        const {previewVisible, previewImage, fileList,token,dis_btn} = this.state,
            {} = this.props;

        return (
            <div className="poduction_manage_tab_box" >
                <div className="product_packagSteps">

                    <div className="product_packagSteps-upload">
                        {/*图片展示系列表*/}
                        {
                            fileList.length !== 0 && fileList.map((item,index)=>
                                <ViewImgList
                                    key={item.file.uid}
                                    imgSrc={`${this.FixedImgSrc + item.file.response.key}`}
                                    imgName={item.file.name}
                                    handlePreview={(e)=>this.handlePreview(index)}
                                    handleRemove={(e)=>this.picRemove(index)}
                                    textValue={item.text}
                                    transClass={item.file.__transClass}   //过渡动画类，中途插入
                                />
                            )
                        }

                        {/*添加图片模版*/}
                        <ViewAAddImg  onClick={this.addImg} />

                        {/*预览图片*/}
                        <Modal visible={previewVisible} className="production_preview" footer={null} width={800} onCancel={this.handleCancel}>
                            <img alt="example" style={{ width: '100%' }} src={previewImage} />
                        </Modal>

                        {/*添加图片弹出框*/}
                        <AddImgModal
                            uploadPlugin = {this.uploadPlugin}   //上传参数配置
                            ref="addFileImgModal"   //ref方便visible显示
                            token={token}   // 上传图片时，必须的token，(此token异步返回)
                            addFileImg={this.addFileImg}   //上传成功的回调，第一个参数的第一个属性为返回的fill,第二个属性为text描述
                            //  text 描述 props配置信息
                            TextProps={{  className:"packagSteps_AddImgModal_textArea",
                                rows:3,
                                placeholder:"请输入描述信息",
                            }}
                            limit={{width:500,height:500}} //最小宽高限制参数
                            save={this.save}
                        />
                    </div>

                    <div className="packagSteps_footer">
                        <Button type="primary"  loading={dis_btn} disabled={dis_btn} onClick={this.save}> 保存 </Button>
                    </div>
                </div>
            </div>
        )
    }
}